package com.jinly.ryder.jenkins.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jinly.ryder.common.service.TemplateService;
import com.jinly.ryder.jenkins.service.JenkinsBuildService;
import com.jinly.ryder.jenkins.service.JenkinsHttpService;
import com.jinly.ryder.jenkins.service.JenkinsJobService;
import com.jinly.ryder.jenkins.service.model.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class JenkinsJobServiceImpl implements JenkinsJobService {
    private final JenkinsHttpService jenkinsHttpService;
    private final JenkinsBuildService jenkinsBuildService;
    private final TemplateService templateService;

    @Override
    public List<JenkinsArtifact> getArtifacts(String jobName) {
        List<JenkinsBuild> buildInfoList = getBuilds(jobName);
        return buildInfoList.stream()
                .filter(b -> "SUCCESS".equals(b.getResult()))
                .flatMap(b -> b.getArtifacts().stream().map(a -> {
                    a.setGitUrl(b.getGitUrl());
                    a.setGitBranch(b.getGitBranch());
                    a.setCommentList(
                            b.getGitCommitLogList().stream()
                                    .map(c -> new CommentMsg(c.getComment()))
                                    .collect(Collectors.toList())
                    );
                    return a;
                }))
                .collect(Collectors.toList());
    }


    @Override
    public List<JenkinsBuild> getBuilds(String jobName) {
        JenkinsJob job = getJenkinsJob(jobName, true);
        if (job != null) {
            return job.getBuildInfoList();
        }
        return null;
    }

    @Override
    public JenkinsJob getJenkinsJob(String jobName, boolean loadBuild) {
        String path = "/job/" + jobName + "/api/json";
        String json = jenkinsHttpService.doGet(path);
        if (json == null) return null;
        JSONObject jsonObject = JSONObject.parseObject(json);
        JenkinsJob jenkinsJob = jsonObject.toJavaObject(JenkinsJob.class);
        jenkinsJob.setJobName(jobName);
        if (loadBuild) {
            List<JenkinsBuild> buildInfoList = jsonObject.getJSONArray("builds").stream().map(o -> {
                Integer number = ((JSONObject) o).getInteger("number");
                JenkinsBuild jenkinsBuild = jenkinsBuildService.getBuild(jobName, number);
                return jenkinsBuild;
            }).collect(Collectors.toList());
            jenkinsJob.setBuildInfoList(buildInfoList);
        }
        return jenkinsJob;
    }


    @Override
    public void createJob(JenkinsJobParam jenkinsJobParam) {
        log.info("开始创建JOB:{}", jenkinsJobParam.getJobName());
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("pipeline", jenkinsJobParam.getPipeline());
        String configXml = templateService.getLocalResult("jenkins/config.xml", paramMap);
        String path = "/createItem?name=" + jenkinsJobParam.getJobName();
        jenkinsHttpService.doPostXml(path, configXml);
    }

    @Override
    public void uploadJob(JenkinsJobParam jenkinsJobParam) {
        log.info("开始更新JOB:{}", jenkinsJobParam.getJobName());
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("pipeline", jenkinsJobParam.getPipeline());
        String configXml = templateService.getLocalResult("jenkins/config.xml", paramMap);
        String path = "/job/" + jenkinsJobParam.getJobName() + "/config.xml";
        jenkinsHttpService.doPostXml(path, configXml);
    }


    @Override
    public void saveJob(JenkinsJobParam jenkinsJobParam) {
        if (getJenkinsJob(jenkinsJobParam.getJobName(), false) == null) {
            createJob(jenkinsJobParam);
        } else {
            uploadJob(jenkinsJobParam);
        }
    }
}
